import { View, Picker } from '@tarojs/components';
import dayjs from 'dayjs';
import { useEffect, useState } from '@tarojs/taro';
import XRow from '../XRow';

const XDate = ({ value, style, onChange, hiddenDate, hiddenTime }) => {
  const [date, setDate] = useState('');
  const [time, setTime] = useState('');
  useEffect(() => {
    if (value) {
      setDate(dayjs(value).format('YYYY-MM-DD'));
      setTime(dayjs(value).format('HH:mm'));
    }
  }, [value]);

  const onChangeValue = (key, e) => {
    const value = e.detail.value;
    if (key === 'date') {
      setDate(value);
    } else {
      setTime(value);
    }
    if (hiddenDate) {
      onChange(time);
    } else if (hiddenTime) {
      onChange(date);
    } else {
      if (date && time) {
        onChange(`${key === 'date' ? value : date} ${key === 'time' ? value : time}`);
      }
    }
  };

  return (
    <XRow style={style}>
      {!hiddenDate && (
        <Picker mode="date" value={date} onChange={onChangeValue.bind(this, 'date')}>
          {date}
        </Picker>
      )}
      {!hiddenTime && (
        <Picker
          mode="time"
          value={time}
          onChange={onChangeValue.bind(this, 'time')}
          style={{ marginLeft: '5px' }}
        >
          {time}
        </Picker>
      )}
    </XRow>
  );
};
XDate.defaultProps = {
  value: '',
  style: {},
  hiddenDate: false,
  hiddenTime: false,
  onChange: () => {}
};
export default XDate;
